package io.github.hadyang.leetcode.offer;

import org.junit.Test;

/**
 * https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 *
 * <p>给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
 */
public class Power {

  @Test
  public void test() {
    System.out.println(Power(5, 2));
    System.out.println(Power(5, 3));
    System.out.println(Power(5, -2));
  }

  public double Power(double base, int exponent) {
    if (base == 0) {
      return 0;
    }

    if (base == 1) {
      return 1;
    }

    int t_exponent = Math.abs(exponent);

    double t = PositivePower(base, t_exponent);

    return exponent > 0 ? t : 1 / t;
  }

  private double PositivePower(double base, int exponent) {
    if (exponent == 0) {
      return 1;
    }

    if (exponent == 1) {
      return base;
    }

    double t = PositivePower(base, exponent >> 1);
    t *= t;
    if ((exponent & 0x01) == 1) {
      t *= base;
    }

    return t;
  }
}
